/*
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2023-03-02 10:18:40
 * @LastEditors: huangtianyang
 * @FilePath: \cxl-h5\src\pages\personalCenter\wallet\pay\index.ts
 */
import { getWalletInfo } from '@/apis/home'
import { getPaySetMeal, wxPay } from '@/apis/wallet'
import { CxlMessage } from '@/components/message'
import { storage } from '@/store/sessionStorage'
import useJudgeLogin from '@/utils/judgeLogin'
import { BasicData } from '@/utils/basicData'
import useWeixinSdk from '@/utils/WXSdk'
import { reactive, ref } from 'vue'

interface setMealList {
    amount: string
    marketAmount: string
    id: string
    packageCount: number
    packageNameNumber: number
    packageTag: string //标签
    productType: number
    sort: number
}

interface setMealItem {
    title: string
    id: number | string
    list: setMealList[]
}

export class PaySet extends BasicData {
    remindVisible = ref(true)
    //套餐类型
    list: setMealItem[] = reactive([
        {
            id: 1,
            title: '出险查询',
            list: []
        },
        {
            id: 2,
            title: '维保查询',
            list: []
        },
        {
            id: 3,
            title: '新能源查询',
            list: []
        }
    ])
    //选择的套餐 默认不选中
    selectIndex = reactive([-1, -1])
    //是否可以选择
    isSelect = ref(true)
    //是否勾选协议
    checked = ref(false)
    //微信用户信息
    wxUserInfo: any = reactive({})
    //钱包信息
    walletInfo: any = reactive({
        title: ['出险次数', '维保次数', '新能源次数'],
        count: [0, 0, 0]
    })
    //支付中
    loadingVisible = ref(false)
    isPending = false
    constructor() {
        super()
        useJudgeLogin.init(() => {
            this.querySetMeal()

            this.getWallet()
        })
        this.wxUserInfo = storage.get('wxUserInfo') ? JSON.parse(storage.get('wxUserInfo')) : null
    }
    getWallet = () => {
        //获取用户钱包
        getWalletInfo().then((res: any) => {
            if (res.data.value === 200) {
                //充值赠送次数
                const productRemainFreeCountKeyValuePairs = res.data.data.productRemainFreeCount
                    .slice(1, -1)
                    .split(/\s*,\s*/)
                    .map((chunk: any) => chunk.split(':'))
                const productRemainFreeCount = new Map(productRemainFreeCountKeyValuePairs)

                //系统免费试用次数
                const productSystemRemainFreeCountMapKeyValuePairs = res.data.data.productSystemRemainFreeCountMap
                    .slice(1, -1)
                    .split(/\s*,\s*/)
                    .map((chunk: any) => chunk.split(':'))
                const productSystemRemainFreeCountMap = new Map(productSystemRemainFreeCountMapKeyValuePairs)

                //套餐次数
                const productRemainNumberPackageCountMapKeyValuePairs = res.data.data.productRemainNumberPackageCountMap
                    .slice(1, -1)
                    .split(/\s*,\s*/)
                    .map((chunk: any) => chunk.split(':'))
                const productRemainNumberPackageCountMap = new Map(productRemainNumberPackageCountMapKeyValuePairs)

                console.log(
                    productRemainFreeCount.get('1') || 0,
                    productSystemRemainFreeCountMap.get('1') || 0,
                    productRemainNumberPackageCountMap.get('1') || 0
                )

                const one =
                    Number(productRemainFreeCount.get('1') || 0) +
                    Number(productSystemRemainFreeCountMap.get('1') || 0) +
                    Number(productRemainNumberPackageCountMap.get('1') || 0) +
                    res.data.data.remainConvertCount
                const two =
                    Number(productRemainFreeCount.get('2') || 0) +
                    Number(productSystemRemainFreeCountMap.get('2') || 0) +
                    Number(productRemainNumberPackageCountMap.get('2') || 0)
                const three =
                    Number(productRemainFreeCount.get('3') || 0) +
                    Number(productSystemRemainFreeCountMap.get('3') || 0) +
                    Number(productRemainNumberPackageCountMap.get('3') || 0)

                this.walletInfo.count[0] = one
                this.walletInfo.count[1] = two
                this.walletInfo.count[2] = three

                console.log(this.walletInfo)
            }
        })
    }
    //获取套餐类型
    querySetMeal = () => {
        getPaySetMeal().then((res: any) => {
            if (res.data.value === 200) {
                this.list[0].list.length = 0
                this.list[1].list.length = 0
                this.list[2].list.length = 0
                const arr: any[] = [[], [], []]
                res.data.data.forEach((item: any) => {
                    arr[item.productType - 1].push({
                        amount: item.amount,
                        id: item.id,
                        marketAmount: item.marketAmount,
                        packageCount: item.packageCount,
                        packageNameNumber: item.packageNameNumber,
                        packageTag: item.packageTag,
                        productType: item.productType,
                        sort: item.sort
                    })
                })

                //排序 递增
                arr[0].sort((a: any, b: any) => {
                    return a.sort - b.sort
                })

                arr[1].sort((a: any, b: any) => {
                    return a.sort - b.sort
                })

                arr[2].sort((a: any, b: any) => {
                    return a.sort - b.sort
                })

                this.list[0].list.push(...arr[0])
                this.list[1].list.push(...arr[1])
                this.list[2].list.push(...arr[2])
            }
        })
    }
    //监听选择的套餐类型
    onSelect = (index: number, i: number) => {
        if (this.isSelect.value) {
            this.selectIndex[0] = index
            this.selectIndex[1] = i

            console.log(this.selectIndex)
        }
    }
    //充值
    onPay = () => {
        this.submitPay()
    }

    submitPay = () => {
        if (this.selectIndex[1] === -1) {
            CxlMessage.error('请选择充值套餐！')
            return false
        } else if (!this.checked.value) {
            CxlMessage.error('请勾选并认真阅读协议内容！')
            return false
        }

        //用户点击充值按钮后，套餐不可选择
        this.isSelect.value = false
        this.loadingVisible.value = true

        if (this.isPending) {
            return
        }
        this.isPending = true

        wxPay(this.wxUserInfo.openid, this.list[this.selectIndex[0]].list[this.selectIndex[1]].id, 1).then(
            (res: any) => {
                //创建订单后，修改状态
                this.isSelect.value = true
                this.isPending = false
                if (res.data.value === 200) {
                    const wxOrderResult = res.data.data.wxOrderResult

                    //唤起支付
                    useWeixinSdk
                        .onChooseWXpay({
                            timestamp: wxOrderResult.timeStamp,
                            nonceStr: wxOrderResult.nonceStr,
                            package: wxOrderResult.packageValue,
                            signType: wxOrderResult.signType,
                            paySign: wxOrderResult.paySign
                        })
                        .then(
                            () => {
                                //支付成功
                                // alert(JSON.stringify(result))
                                //刷新钱包信息
                                this.getWallet()
                                this.loadingVisible.value = false
                            },
                            () => {
                                //取消支付 | 支付失败
                                this.loadingVisible.value = false
                            }
                        )
                } else {
                    this.loadingVisible.value = false
                }
            },
            () => {
                this.isSelect.value = true
                this.isPending = false
            }
        )
    }

    //打开页面 1 钱包记录
    onOpenPage = () => {
        this.router.push('/wallet/record')
    }
    /**
     * 打开协议
     */
    onOpenProtocol = (type: string) => {
        this.router.push({ name: 'protocol', params: { type } })
    }
    //打开退款页面
    openRefund = () => {
        this.router.push('/refund/make-out')
    }
    onNaviagate = (url: string) => {
        this.router.push(url)
    }
}
